﻿using LiteBlog.Common.Components;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using WURFL;

namespace LiteBlog.Controllers.Helpers
{
    class DeviceHelper
    {
        private static readonly string ResolutionWidthCapability = "resolution_width";
        private static readonly string ResolutionHeightCapability = "resolution_height";
        // private static readonly string ImageWidthCapability = "max_image_width";
        // private static readonly string ImageHeightCapability = "max_image_height";

        private static readonly int DefaultWidth = 768;
        private static readonly int DefaultHeight = 1024;
        internal static int GetDeviceWidth(IWURFLManager manager, string userAgent)
        {
            if (manager == null)
                return DefaultWidth;

            int width = DefaultWidth;
            int height = DefaultHeight;
            int imageWidth = DefaultWidth;
            int imageHeight = DefaultHeight;
            string viewportWidth = string.Empty;

            var device = manager.GetDeviceForRequest(userAgent, MatchMode.Performance);
            if (device != null)
            {
                var widthString = device.GetCapability(ResolutionWidthCapability);
                var heightString = device.GetCapability(ResolutionHeightCapability);
                //var imageWidthString = device.GetCapability(ImageWidthCapability);
                //var imageHeightString = device.GetCapability(ImageHeightCapability);
                //viewportWidth = device.GetCapability(ViewportWidthCapability);

                if (!int.TryParse(widthString, out width))
                    width = DefaultWidth;
                if (!int.TryParse(heightString, out height))
                    height = DefaultHeight;
                //if (!int.TryParse(imageWidthString, out imageWidth))
                //    imageWidth = DefaultWidth;
                //if (!int.TryParse(imageHeightString, out imageHeight))
                //    imageHeight = DefaultHeight;
            }
            Logger.Debug(string.Format("Device: {0} Width: {1} Height: {2} Image Width: {3} Image Height: {4} Viewport: {5}", device.NormalizedUserAgent, width, height, imageWidth, imageHeight, viewportWidth));
            return width;
        }
    }
}
